package com.chengcang.admin.common.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.chengcang.admin.modules.security.user.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fankunfeng
 * @date 2023-01-28 10:30:41
 **/
@Component
@Slf4j
public class TenantHandler implements TenantLineHandler {

    @Value("${chengcang.excludeTables}")
    private String excludeTables;

    @Override
    public Expression getTenantId() {
        Long tenantId = SecurityUser.getTenantId();
        if (tenantId != null) {
            return new LongValue(tenantId);
        }
        return null;
    }

    @Override
    public boolean ignoreTable(String tableName) {
        if (getTenantId() != null) {
            // 不补充租户过滤条件的表
            List<String> asList = Arrays.stream(excludeTables.split(",")).collect(Collectors.toList());
            return asList.contains(tableName);
        }
        return true;
    }
}
